package com.voltmao.webpro.utils.wechat.utils;

import com.voltmao.webpro.utils.JsonUtil;
import com.voltmao.webpro.utils.http.HttpClientUtil;
import com.voltmao.webpro.utils.wechat.IWechatUtils;
import com.voltmao.webpro.utils.wechat.core.AccessToken;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by zhouyang on 2017/7/14.
 * 微信二维码工具
 */
public class QRCodeUtils {

    private AccessToken accessToken;
    private Map<String, String> wxConfig;

    private static Logger logger = Logger.getLogger(QRCodeUtils.class.getName());


    public QRCodeUtils(IWechatUtils wechatUtils) {
        this.accessToken = wechatUtils.getAccessToken();
        this.wxConfig = wechatUtils.getWxConfig();
    }

    public QRCodeUtils() {

    }

    /**
     * 生成临时性 关注二维码
     *
     * @param params
     * @return
     */
    public String createTempQRCode(Map<String, Object> params) {
        String sendUrl = this.wxConfig.get("wx.subscribe.qrcode").replace("ACCESS_TOKEN", accessToken.getAccessToken());

        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("expire_seconds", "2592000");
        sendMap.put("action_name", "QR_SCENE");
        sendMap.put("action_info", "{'scene':jsonData}".replace("jsonData", JsonUtil.ObjectToJSON(params)));

        Map<String, Object> resultMap = JsonUtil.ToMap(HttpClientUtil.sendPostToString(sendUrl, JsonUtil.ObjectToJSON(sendMap)));
        return resultMap.get("url") + "";
    }

    /**
     * 生成永久性二维码
     *
     * @param params
     * @return
     */
    public String createForeverQRCode(Map<String, Object> params) {
        String sendUrl = this.wxConfig.get("wx.subscribe.qrcode").replace("ACCESS_TOKEN", accessToken.getAccessToken());

        String requestStr = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": jsonData".replace("jsonData", JsonUtil.ObjectToJSON(params));

        Map<String, Object> resultMap = JsonUtil.ToMap(HttpClientUtil.sendPostToString(sendUrl, requestStr));
        return resultMap.get("url") + "";
    }


    public static void main(String[] args) {
        QRCodeUtils qrCodeUtils = new QRCodeUtils();

        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("x1", "1231");
        sendMap.put("x2", "003");

        qrCodeUtils.createTempQRCode(sendMap);
    }
}
